#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    return HelloWorld::create();
}

// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
    printf("Error while loading: %s\n", filename);
    printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
	//////////////////////////////
	// 1. super init first
	if (!Scene::init())
	{
		return false;
	}

	visibleSize = Director::getInstance()->getVisibleSize();

	startGame();

	auto listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = [](Touch* t, Event* e)
	{
		log("onTouch");

		return false;
	};

	Director::getInstance()->getEventDispatcher()->
		addEventListenerWithSceneGraphPriority(listener, this);
	
	return true;
}

void HelloWorld::startGame()
{
	addStartLine(0);
	addNormalLine(1);
	addNormalLine(2);
	addNormalLine(3);
	//addEndLine();
}


void HelloWorld::addStartLine(int lineIndex)
{
	Block *block;
	int lineCount = 4;
	for (int i = 0; i < lineCount; i++)
	{
		int blackIndex = rand() % 4;
		block = Block::createWithArgs(blackIndex == i ? Color3B::BLACK : Color3B::WHITE,
			Size(visibleSize.width / 4 - 1, visibleSize.height / 4 - 1),
			blackIndex == i ? "START" : "" , 32, blackIndex == i ? Color4B::WHITE : Color4B::BLACK);

		addChild(block);

		block->setPosition(i * visibleSize.width / 4, lineIndex * visibleSize.height / 4);
		block->setLineIndex(lineIndex);
	}
}


void HelloWorld::addEndLine()
{
	auto block = Block::createWithArgs(Color3B::YELLOW, visibleSize, "", 32, Color4B::BLACK);
	addChild(block);

	block->setLineIndex(4);

}

void HelloWorld::addNormalLine(int lineIndex)
{
	Block *block;
	int lineCount = 4;
	for (int i = 0 ; i < lineCount; i++)
	{
		int blackIndex = rand() % 4;
		block = Block::createWithArgs(blackIndex == i ? Color3B::BLACK:Color3B::WHITE,
				Size(visibleSize.width / 4 - 1, visibleSize.height / 4 - 1), "", 32, Color4B::BLACK);
		
		addChild(block);

		block->setPosition(i * visibleSize.width / 4 , lineIndex * visibleSize.height / 4);
		block->setLineIndex(lineIndex);
	}

	linesCount++;
}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
    //Close the cocos2d-x game scene and quit the application
    Director::getInstance()->end();

    #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif

    /*To navigate back to native iOS screen(if present) without quitting the application  ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/

    //EventCustom customEndEvent("game_scene_close_event");
    //_eventDispatcher->dispatchEvent(&customEndEvent);


}
